package com.training.utils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * URL工具类，用于构建完整的URL路径
 */
public class UrlUtils {
    
    /**
     * 构建完整的URL，参考FileUploadUtil的方式
     * @param request HTTP请求对象
     * @param path 资源路径
     * @return 完整的URL
     */
    public static String buildFullUrl(HttpServletRequest request, String path) {
        if (request == null) {
            return path;
        }
        
        // 检查是否有X-Forwarded-Proto头部，用于处理反向代理的情况
        String scheme = request.getHeader("X-Forwarded-Proto");
        if (scheme == null || scheme.isEmpty()) {
            scheme = request.getScheme(); // http 或 https
        }
        
        String serverName = request.getServerName();     // localhost 或域名
        int serverPort = request.getServerPort();        // 端口号
        String contextPath = request.getContextPath();   // 上下文路径
        
        // 处理反向代理的情况，检查X-Forwarded-Host头部
        String forwardedHost = request.getHeader("X-Forwarded-Host");
        if (forwardedHost != null && !forwardedHost.isEmpty()) {
            serverName = forwardedHost;
        }
        
        // 处理反向代理的情况，检查X-Forwarded-Port头部
        String forwardedPort = request.getHeader("X-Forwarded-Port");
        if (forwardedPort != null && !forwardedPort.isEmpty()) {
            try {
                serverPort = Integer.parseInt(forwardedPort);
            } catch (NumberFormatException e) {
                // 如果解析失败，保持原有端口号
            }
        }

        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://").append(serverName);

        // 如果不是默认端口，则添加端口号
        if ((scheme.equals("http") && serverPort != 80) ||
                (scheme.equals("https") && serverPort != 443)) {
            url.append(":").append(serverPort);
        }

        // 确保路径正确连接
        if (!contextPath.endsWith("/") && !path.startsWith("/")) {
            url.append(contextPath).append("/").append(path);
        } else {
            url.append(contextPath).append(path);
        }

        return url.toString();
    }
}